var createBy = localStorage.getItem("username");
var dataPacketFileName = localStorage.getItem('dataPacketFileName');
const ComponentHome = (() => {
  // 添加样式（确保只添加一次）
  if (!document.getElementById('home-style')) {
    const style = document.createElement('style');
    style.id = 'home-style';  // 添加唯一ID
    style.textContent = `
          @media (max-width: 768px) {
              .manual-grid {
                  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                  gap: 20px;
                  padding: 10px;
              }

              .manual-book img {
                  width: 120px;
                  height: 160px;
              }

              .header-content h1 {
                  font-size: 20px;
              }
          }
      `;
    document.head.appendChild(style);
  }

  // 返回组件配置
  return {
    template: `
          <div class="home-page">
              <header class="page-header">
                  <div class="header-content">
                      <h1 id="header_title">交互式电子技术手册</h1>
                  </div>
                  <div class="nav_list">
                    <li class="_left" @click="onCollect()">{{ isCollect ? '左侧展开' : '左侧收起' }}</li>
                    <li class="_left quxian"><span class="_tui" @click="operation(0)">后退</span> <span class="xiexian">/</span> <span class="_qian" @click="operation(1)">前进</span></li>
                    <li class="_left" @click="goHome()">主页</li>
                    <li class="kong"></li>
                    <li class="_right history" @click="onHistory()">历史记录 <div id="history_list" tabindex="1"></div></li>
                    <li class="_right remarks" @click="onRemarks()">备注 <div id="remarks_list" tabindex="2"></div></li>
                    <li class="_right" @click="shuoding()">锁屏</li>
                  </div>
                  
                  <div class="btn_box">
                      <span>{{ userName }}</span>
                      <div class="logout-box">
                          <button type="button" class="layui-btn layui-btn-sm  layui-btn-radius"  @click="removeProjet(true)">删除项目</button>
                          <button type="button" class="layui-btn layui-btn-sm  layui-btn-radius"  @click="modifyPassword">修改密码</button>
                          <button type="button" class="layui-btn layui-btn-sm  layui-btn-radius"  @click="logout()">退出登录</button>
                      </div>
                  </div>
              </header>
              
              <div class="manual-container">
                  <div class="imgts" ></div>
                  <div class="manual-grid">
                      <div class="manual-item" v-for="(item, index) in manuals" :key="index">
                          <div class="manual-book" @click="bookClick(item)">
                              <img src="./img/xm_bg1.png" :alt="item">
                              <img src="./img/bg_icon1.png" alt="" class="book_icon" />
                              
                              <div class="before"  @click.stop="removeProjet(false, item)">
                                <svg t="1733883980551" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3103"><path d="M512 883.2A371.2 371.2 0 1 0 140.8 512 371.2 371.2 0 0 0 512 883.2z m0 64a435.2 435.2 0 1 1 435.2-435.2 435.2 435.2 0 0 1-435.2 435.2z" p-id="3104"></path><path d="M557.056 512l122.368 122.368a31.744 31.744 0 1 1-45.056 45.056L512 557.056l-122.368 122.368a31.744 31.744 0 1 1-45.056-45.056L466.944 512 344.576 389.632a31.744 31.744 0 1 1 45.056-45.056L512 466.944l122.368-122.368a31.744 31.744 0 1 1 45.056 45.056z" p-id="3105"></path></svg>
                              </div>
                              <h3>{{item}}</h3>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      `,
    // <div class="suoding" title="锁定页面"  @click="shuoding">
    //   <img src="./img/shuo.png" alt="">
    // </div>
    // <img src="./img/remove.png" alt="" class="before" />
    data() {
      return {
        userName: '',
        isCollect: false,
        manuals: [] // 创建8个手册项
      }
    },
    created() {
      var createBy = localStorage.getItem("username");
      var dataPacketFileName = localStorage.getItem('dataPacketFileName');
      let _this = this;
      $.ajax({
        type: "GET",
        url: '/ietm/homePage/list',
        data: {},
        dataType: "JSON",
        success: function (res) {
          if (res.code == 200) {
            console.log(res);
            _this.manuals = res.data;
            // _this.manuals  = ['222','测试1']
            localStorage.setItem('dataPacketNum', res.data.length)
            // 只有一个包 默认直接进入内页
            if (res.data.length === 1) {
              _this.bookClick(res.data[0])
            }

            // if (!localStorage.getItem('dataPacketFileName')) {
            //   if (res.data.length) {
            //     localStorage.setItem('dataPacketFileName', res.data[0])
            //   }
            // }
            if (!res.data.length) {
              layer.msg('暂无数据 !');
            }
          } else {
            if (res.msg.includes("未登录")) {
              layer.msg('用户未登录!');
              // setTimeout(function () {
                window.wlogout()
              // }, 1500);
              return false;
            } else {
              layer.msg('获取数据失败 !');
            }
          }
        }, error: function (res) {
          layer.msg('获取数据失败 !');
        }
      })
    },
    mounted() {
      this.userName = localStorage.getItem('username');
    },
    methods: {
      // 添加 cookie 检查函数
      getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
      },
      logout() {
        let _this = this;

        layer.confirm('是否确认退出登录?', function (index) {
          $.ajax({
            type: "POST",
            url: '/ietm/logout',
            success: function (res) {
              if (res.code == 200) {
                layer.msg('退出成功 !');
                document.cookie = "systemToken=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; // 删除cookie中的token
                sessionStorage.removeItem('systemToken');
                localStorage.removeItem('username');
                localStorage.removeItem('userInfo');

                localStorage.removeItem('dataModuleFileName');
                localStorage.removeItem('dataModuleName');
                localStorage.removeItem('dataPacketFileName');
                localStorage.removeItem('isCollect');
                _this.$router.push('/login')
              } else {
                layer.msg('退出失败 !');
              }
            }, error: function (res) {
              layer.msg('退出失败 !');
            }
          })
          layer.close(index);
        })
      },
      shuoding() {
        layer.confirm('是否确认锁定页面?', function (index) {
          console.log("锁定页面");
          $('.shuoding_box').css({ 'display': 'flex' });
          let username = localStorage.getItem('username');
          $('#id_user_name').html(username);
          sessionStorage.setItem('isLocking', 'true');
          layer.close(index);
        })
      },
      onCollect() {
        // this.isCollect = !this.isCollect;
      },
      bookClick(item) {
        // 模拟点击事件，跳转到相应页面
        // window.location.href = '/manual/maintain.html';
        console.log(item, '231131313');

        this.$router.replace({
          path: "/details",
          query: {
            path: item,
          },
        });
      }
    }
  };
})();

function deleteItem(dataModuleFileName) {
  event.stopPropagation();
  console.log(dataModuleFileName);
  var dataPacketFileName = localStorage.getItem('dataPacketFileName');
  function apiF() {
    $.ajax({
      type: "DELETE",
      url: '/ietm/history/delete',
      data: {
        "dataPacketFileName": dataPacketFileName,
        "dataModuleFileName": dataModuleFileName,
        "createBy": localStorage.getItem("username"),
        "isEmpty": dataModuleFileName ? 0 : 1
      },
      dataType: "JSON",
      success: function (res) {
        if (res.code == 200) {
          layer.msg('删除成功 !');
          var historyList = `
          <div class="title_box">
            <p>历史记录</p><span class="delete_span" id="" onclick="deleteItem('')">清空记录</span>
          </div>`
          historyList += res.data.map(function (item, index) {
            return `
            <a id="tree_${index}_a" class="level" title="${item.dataModuleName}" onclick="historyItemClick('${item.dataModuleFileName}', '${item.dataPacketFileName}', '${item.dataModuleName}', '')">
              <span id="tree_${index}_ico" class="button ico_docu"></span>
              <span id="tree_${index}_span" class="tree_span">${item.dataModuleName}</span>
              <span class="delete_span" id="" onclick="deleteItem('${item.dataModuleFileName}')">删除</span>
            </a>
          `;
          }).join('');
          $(".nav_list #history_list").html(historyList);
          if (!res.data.length) {
            $(".nav_list #history_list").hide();
          }
        } else {
          if (res.msg.includes("未登录")) {
            layer.msg('用户未登录!');
            setTimeout(function () {
              parent.wlogout()
            }, 1500);
            return false;
          } else {
            layer.msg('获取失败 !');
          }
        }
      }, error: function (res) {
        layer.msg('请求失败 !');
      }
    })
  }

  if (dataModuleFileName) {
    apiF();
  } else {
    layer.confirm('确定清空记录吗？', function (index) {
      apiF();
      layer.close(index); // 关闭弹窗
    });
  }
}


function deleteRemarksItem(dataModuleFileName, id) {
  event.stopPropagation();
  var dataPacketFileName = localStorage.getItem('dataPacketFileName');
  var serid = id || '';
  function apiF() {
    $.ajax({
      type: "DELETE",
      url: '/ietm/remarks/delete',
      data: {
        "id": serid,
        "dataPacketFileName": dataPacketFileName,
        "dataModuleFileName": dataModuleFileName,
        "createBy": localStorage.getItem("username"),
        "isEmpty": dataModuleFileName ? 0 : 1
      },
      dataType: "JSON",
      success: function (res) {
        if (res.code == 200) {
          layer.msg('删除成功 !');
          let historyList = `
          <div class="title_box">
            <p>备注列表</p><span class="delete_span" id="" onclick="deleteRemarksItem('')">清空备注</span>
          </div>`
          historyList += res.data.map(function (item, index) {
            return `
            <a id="tree_${index}_a" class="level" title="${item.dataModuleName}" onclick="historyItemClick('${item.dataModuleFileName}', '${item.dataPacketFileName}', '${item.dataModuleName}', '${item.id})">
              <span id="tree_${index}_ico" class="button ico_docu"></span>
              <span id="tree_${index}_span" class="tree_span">${item.dataModuleName}: ${item.remarksContent}</span>
              <span class="delete_span" id="" onclick="deleteRemarksItem('${item.dataModuleFileName}', '${item.id}')">删除</span>
            </a>
          `;
          }).join('');
          $(".nav_list #remarks_list").html(historyList);
          var localStorageDataModuleFileName = localStorage.getItem('dataModuleFileName');
          if (!dataModuleFileName || dataModuleFileName === localStorageDataModuleFileName && $("#contentFrame").length) {
            const outerIframe = $('#contentFrame'); // 外层 iframe
            console.log('// DOM 元素存在，可以进行后续操作');
            // 等待外层 iframe 加载完成后
            const outerDoc = outerIframe.contents(); // 获取外层 iframe 的文档对象
            const innerIframe = outerDoc.find('#htmlBrowse'); // 查找外层 iframe 中的内层 iframe
            console.log('// DOM 元素存在，可以进行后续操作12', innerIframe);

            const originalContent = innerIframe[0].innerHTML;
            innerIframe[0].innerHTML = "";
            // setTimeout(function () {
            innerIframe[0].innerHTML = originalContent;
            // }, 200);
            $(".nav_list #remarks_list").hide();
          }
          if (!res.data.length) {
            $(".nav_list #remarks_list").hide();
          }
        } else {
          if (res.msg.includes("未登录")) {
            layer.msg('用户未登录!');
            setTimeout(function () {
              parent.wlogout()
            }, 1500);
            return false;
          } else {
            layer.msg('获取失败 !');
          }
        }
      }, error: function (res) {
        layer.msg('请求失败 !');
      }
    })
  }

  if (dataModuleFileName) {
    apiF();
  } else {
    layer.confirm('确定清空记录吗？', function (index) {
      apiF();
      layer.close(index); // 关闭弹窗
    });
  }
}

function historyItemClick(dataModuleFileName, dataPacketFileName, dataModuleName, id) {
  localStorage.setItem('dataModuleFileName', dataModuleFileName);
  localStorage.setItem('dataPacketFileName', dataPacketFileName);
  localStorage.setItem('dataModuleName', dataModuleName);
  console.log(dataModuleName, '3127391739');

  event.stopPropagation();
  // http://127.0.0.1:8079/#/details?path='测试1'
  $(".nav_list #history_list").blur();
  $(".nav_list #history_list").blur();
  $(".nav_list #remarks_list").hide();
  $(".nav_list #remarks_list").hide();

  location.replace(window.location.origin + '/ietmData/#/details?path=' + dataPacketFileName + '&dmName=' + dataModuleFileName + '&id=' + id);
  // nginx
  // location.replace(window.location.origin + '/#/details?path=' + dataPacketFileName + '&dmName=' + dataModuleFileName + '&id=' + id);

}

$(document).on('blur', '#history_list', () => {
  console.log('失去焦点: 历史记录列表失去焦点!');
  $(".nav_list #history_list").hide();
});

$(document).on('blur', '#remarks_list', () => {
  console.log('失去焦点: 备注列表失去焦点!');
  $(".nav_list #remarks_list").hide();
});


function onRemarks() {
  var dataPacketFileName = localStorage.getItem('dataPacketFileName');
  var dataModuleFileName = localStorage.getItem('dataModuleFileName');
  if (!dataPacketFileName) {
    layer.msg('暂无备注数据 !');
    return false;
  }
  $.ajax({
    type: "GET",
    url: '/ietm/remarks/list',
    data: {
      "dataPacketFileName": dataPacketFileName,
      "createBy": localStorage.getItem("username"),
      // "dataModuleFileName": dataModuleFileName
    },
    dataType: "JSON",
    success: function (res) {
      if (res.code == 200) {
        let historyList = `
          <div class="title_box">
            <p>备注列表</p><span class="delete_span" id="" onclick="deleteRemarksItem('')">清空备注</span>
          </div>`
        historyList += res.data.map(function (item, index) {
          return `
            <a id="tree_${index}_a" class="level" title="${item.dataModuleName}" onclick="historyItemClick('${item.dataModuleFileName}', '${item.dataPacketFileName}', '${item.dataModuleName}', '${item.id}')">
              <span id="tree_${index}_ico" class="button ico_docu"></span>
              <span id="tree_${index}_span" class="tree_span">${item.dataModuleName}: ${item.remarksContent}</span>
              <span class="delete_span" id="" onclick="deleteRemarksItem('${item.dataModuleFileName}', '${item.id}')">删除</span>
            </a>
          `;
        }).join('');
        $(".nav_list #remarks_list").html(historyList);
        if (!res.data.length) {
          $(".nav_list #remarks_list").hide();
          layer.msg('暂无备注数据 !');
          return;
        }
        $(".nav_list #remarks_list").show();
        $(".nav_list #remarks_list").focus();


      } else {
        if (res.msg.includes("未登录")) {
          layer.msg('用户未登录!');
          setTimeout(function () {
            wlogout()
          }, 1500);
          return false;
        } else {
          layer.msg('请求失败 !');
        }
      }
    }, error: function (res) {
      layer.msg('请求失败 !');
    }
  })
}

function onHistory() {
  var dataPacketFileName = localStorage.getItem('dataPacketFileName');
  $.ajax({
    type: "GET",
    url: '/ietm/history/list',
    data: {
      "dataPacketFileName": dataPacketFileName,
      "createBy": localStorage.getItem("username"),
    },
    dataType: "JSON",
    success: function (res) {
      if (res.code == 200) {
        console.log(res, localStorage.getItem("username"));
        let historyList = `
          <div class="title_box">
            <p>历史记录</p><span class="delete_span" id="" onclick="deleteItem('')">清空记录</span>
          </div>`
        historyList += res.data.map(function (item, index) {
          return `
            <a id="tree_${index}_a" class="level" title="${item.dataModuleName}" onclick="historyItemClick('${item.dataModuleFileName}', '${item.dataPacketFileName}', '${item.dataModuleName}', '')">
              <span id="tree_${index}_ico" class="button ico_docu"></span>
              <span id="tree_${index}_span" class="tree_span">${item.dataModuleName}</span>
              <span class="delete_span" id="" onclick="deleteItem('${item.dataModuleFileName}')">删除</span>
            </a>
          `;
        }).join('');
        $(".nav_list #history_list").html(historyList);
        if (!res.data.length) {
          $(".nav_list #history_list").hide();
          layer.msg('暂无历史记录 !');
          return;
        }
        $(".nav_list #history_list").show();
        $(".nav_list #history_list").focus();


      } else {
        if (res.msg.includes("未登录")) {
          layer.msg('用户未登录!');
          setTimeout(function () {
            wlogout()
          }, 1500);
          return false;
        } else {
          layer.msg('请求失败 !');
        }
      }
    }, error: function (res) {
      layer.msg('请求失败 !');
    }
  })
}
{/* <div class="operation_box">
  <div class="home_icon" onclick="goHome()"><img src="./img/home_icon.png" title="返回主页" /></div>
  <div class="left"><img title="后退" onclick="operation(0)" src="./img/left_icon.png" alt=""></div>
  <div class="right"><img title="前进" onclick="operation(1)" src="./img/left_icon.png" alt=""></div>
  <div class="history"><img title="历史记录" onclick="history()" src="./img/history_icon.png" alt="">
    <div id="history_list" tabindex="1"></div>
  </div>
  <div class="suoding" title="锁定页面" onclick="shuoding()"><img src="./img/shuo.png" alt=""></div>
</div> */}
function operation(num) {
  if (num === 1) {
    window.history.go(1);
    // window.location.reload();
    // window.history.forward();
  } else {
    window.history.go(-1); // 后退
    // window.location.reload();
    // window.history.back();
  }
}


function shuoding() {
  console.log("锁定页面", $('.shuoding_box'));
  $(document).find('.shuoding_box').css({ 'display': 'flex' });
  let username = localStorage.getItem('username');
  $(document).find('#id_user_name').html(username);
  sessionStorage.setItem('isLocking', 'true');
}

function goHome() {
  // this.$router.push('/');
  location.replace(window.location.origin + '/ietmData/#/home');
  // location.replace(window.location.origin + '/#/home'); // nginx
}

function removeProjet(bool, name) {
  console.log('237730179301');
  if (bool) {
    $('.manual-book .before').show();
  } else {
    layer.confirm('是否确认删除该项目?', function (index) {
      $.ajax({
        type: "delete",
        url: '/ietm/homePage/delDataPacket',
        data: {
          "dataPacketFileName": name
        },
        dataType: "JSON",
        success: function (res) {
          if (res.code == 200) {
            layer.msg('删除成功 !');
            location.reload();
          }
        }
      })
      layer.close(index);
    })


  }
}

function modifyPassword() {
  let layer = layui.layer;
  let form = layui.form;
  let userName = localStorage.getItem("username");
  const layerIndex = layer.open({
    type: 1,
    area: '350px',
    resize: false,
    shadeClose: true,
    title: '用户注册',
    content: `
          <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
            <div class="demo-login-container">
              <!-- 用户名输入框 -->
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <input 
                    type="text" 
                    name="username" 
                    lay-verify="required|username" 
                    placeholder="用户名 (5位数字/字母)" 
                    lay-reqtext="请填写用户名" 
                    autocomplete="off" 
                    class="layui-input" 
                    lay-affix="clear"
                    disabled
                    value="${userName}">
                </div>
              </div>
              <!-- 密码输入框 -->
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <input 
                    type="password" 
                    name="password" 
                    id="shuoding_box_password"
                    autocomplete="new-password" 
                    lay-verify="required|password" 
                    placeholder="旧密码" 
                    lay-reqtext="请输入旧密码" 
                    autocomplete="off" 
                    class="layui-input" 
                    lay-affix="eye">
                </div>
              </div>
              <!-- 确认密码输入框 -->
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <input 
                    type="password" 
                    name="newPassword" 
                    lay-verify="required|confirmPwd" 
                    placeholder="新密码 (5位以上数字/字母)" 
                    lay-reqtext="请输入新密码" 
                    autocomplete="off" 
                    class="layui-input" 
                    lay-affix="eye">
                </div>
              </div>
              <!-- 提交按钮 -->
              <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">修改密码</button>
              </div>
            </div>
          </div>
        `,
    success: function () {
      // 对弹层中的表单进行初始化渲染
      form.render();

      // 自定义表单校验规则
      form.verify({
        // password: function (value) {
        //   if (!/^[A-Za-z0-9]{5,}$/.test(value)) {
        //     layer.msg('密码必须是5位以上数字或大小写字母');
        //     return true;
        //   }
        // },
        confirmPwd: function (value) {
          if (!/^[A-Za-z0-9]{5,}$/.test(value)) {
            layer.msg('新密码必须是5位以上数字或大小写字母');
            return true;
          }
        }
      });

      // 表单提交事件
      form.on('submit(demo-login)', function (data) {
        const field = data.field; // 获取表单字段值
        // 显示填写结果，仅作演示用
        // layer.alert(JSON.stringify(field), {
        //   title: '当前填写的字段值'
        // });
        console.log(JSON.stringify(field), '2301730173');

        $.ajax({
          type: "POST",
          url: '/ietm/user/update',
          data: {
            "userName": field.username,
            "password": field.password,
            "newPassword": field.newPassword,
          },
          dataType: "JSON",
          success: function (res) {
            console.log(res, '3938219');

            if (res.code == 200) {
              layer.msg('修改成功 !');
              layer.close(layerIndex);
              // _this.username = field.username;
              // _this.password = field.password;
            } else {
              if (res.msg.includes('失败')) {
                layer.msg(res.msg);
              } else {
                layer.msg('修改失败 !');
              }
            }
          }, error: function (res) {
            if (res.msg.includes('失败')) {
              layer.msg(res.msg);
            } else {
              layer.msg('修改失败 !');
            }
          }
        })
        return false; // 阻止默认 form 跳转
      });
    }
  });

}

